<template>
    <el-container>
        <el-main>
            <!-- 筛选部分 -->
            <el-row class="filter-row">
                <el-col :span="13">
                    <el-select v-model="selectCell" placeholder="选择单元楼" style="width: 15vw">
                        <el-option v-for="item in cells" :key="item.value" :value="item.value" />
                    </el-select>
                    <el-select v-model="selectFloor" placeholder="选择楼层数" style="width: 15vw">
                        <el-option v-for="item in floorValues" :key="item.value" :value="item.value" />
                    </el-select>
                    <el-select v-model="selectRoom" placeholder="选择房间号" style="width: 15vw">
                        <el-option v-for="item in roomValues" :key="item.value" :value="item.value" />
                    </el-select>
                </el-col>
                <el-col :span="5">
                    <el-button type="primary" @click="filterBeds">筛选</el-button>
                    <el-button type="primary" @click="allBeds">全部床位</el-button>
                </el-col>
                <!-- 编辑楼房信息按钮 -->
                <div class="setTourPrice"> <el-button type="primary" @click="openBuildingDialog">编辑楼房信息</el-button>
                </div>
            </el-row>

            <!-- 表格部分 -->
            <el-table :data="filteredBedrooms" border>
                <el-table-column label="床位编号" prop="bedId" width="120"></el-table-column>
                <el-table-column label="住户性别" prop="assignedUserGender" width="180"></el-table-column>
                <el-table-column label="住宿楼" prop="buildingNo" width="150"></el-table-column>
                <el-table-column label="楼层号" prop="floorNo" width="150"></el-table-column>
                <el-table-column label="房间号" prop="roomNo" width="150"></el-table-column>
                <el-table-column label="床位号" prop="bedNo" width="100"></el-table-column>
                <el-table-column label="价格" prop="price" width="120">
                    <template #default="{ row }">
                        ¥{{ row.price }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <!-- <el-button @click="editBed(row)">编辑</el-button> -->
                        <el-button @click="deleteBed(row)" type="danger" :disabled="row.assignedUserGender !== ''">
                            删除床位
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 编辑楼房信息的弹窗 -->
            <el-dialog v-model="buildingDialogVisible" title="编辑楼房信息" width="800px">
                <el-form :model="buildingForm" ref="buildingFormRef" label-width="120px">
                    <el-form-item label="建筑楼">
                        <el-input v-model="buildingForm.buildingNo" placeholder="请输入建筑楼信息"></el-input>
                    </el-form-item>
                    <el-form-item label="楼层">
                        <el-input v-model="buildingForm.floorNo" placeholder="请输入楼层"></el-input>
                    </el-form-item>
                    <el-form-item label="房间和床位信息">
                        <el-table :data="buildingForm.rooms" border>
                            <el-table-column label="房间编号" prop="roomNo" width="150">
                                <template #default="{ row, $index }">
                                    <el-input v-model="row.roomNo" placeholder="请输入房间编号"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="床位数量" prop="bedCount" width="150">
                                <template #default="{ row, $index }">
                                    <el-input-number v-model="row.bedCount" :min="1"
                                        placeholder="请输入床位数量"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="价格" prop="price" width="150">
                                <template #default="{ row, $index }">
                                    <el-input-number v-model="row.price" :min="0" placeholder="请输入价格"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100">
                                <template #default="{ row, $index }">
                                    <el-button type="danger" @click="removeRoom($index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-button type="primary" @click="addRoom">添加房间</el-button>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="buildingDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveBuildingInfo">保存</el-button>
                </span>
            </el-dialog>
        </el-main>
    </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import type { Bed } from '../../API/interface/bedManagement'
import { addBed, getAllBeds, deleteBedAPI, screenBeds } from '@/API/interface/bedManagement'
import { ElMessage } from 'element-plus';

// 初始楼和用户编号
const allBedInfo = ref([]);  //获取所有床位信息
// const bedInfo = ref({});//筛选楼房
const filteredBedrooms = ref<Bed[]>([]); // 修正为 Bed 类型
const selectCell = ref('') //选中单元楼
const selectFloor = ref('') ///选中楼层
const selectRoom = ref('') //选中房间



//获取所有床位信息
onMounted(async () => {
    const res = await getAllBeds();
    console.log("获取所有床位", res.data);
    allBedInfo.value = res.data.data;  //把所有床位信息存到allBedInfo里面
    console.log("allBedInfo", allBedInfo.value);

    // 将allBedInfo中的数据映射到bedrooms中
    filteredBedrooms.value = allBedInfo.value.map((bed: any) => ({
        bedId: bed.bedId,
        buildingNo: bed.buildingNo,
        roomNo: bed.roomNo,
        floorNo: bed.floorNo,
        bedNo: bed.bedNo,
        assignedUserGender: bed.status === '空' ? '' : bed.gender, // 如果床位状态为空，则分配用户为空
        price: bed.price,
    }));
    console.log('表格数据', filteredBedrooms.value);


    // 动态填充楼房、楼层、房间和床位信息
    const uniqueBuildings = new Set<string>();
    const uniqueFloors = new Set<string>();
    const uniqueRooms = new Set<string>();
    const uniqueBeds = new Set<string>();

    res.data.data.forEach((bed: any) => {
        uniqueBuildings.add(bed.buildingNo);
        uniqueFloors.add(bed.floorNo);
        uniqueRooms.add(bed.roomNo);
        uniqueBeds.add(bed.bedNo);
    });

    cells.value = Array.from(uniqueBuildings).map(building => ({ value: building }));
    floorValues.value = Array.from(uniqueFloors).map(floor => ({ value: floor }));
    roomValues.value = Array.from(uniqueRooms).map(room => ({ value: room }));
    bedValues.value = Array.from(uniqueBeds).map(bed => ({ value: bed }));
});
const cells = ref([
    { value: '' }
]);

const floorValues = ref([
    { value: '' }
]);
const roomValues = ref([
    { value: '' }
]);
const bedValues = ref([
    { value: '' }
]);

// 筛选床位的函数
const filterBeds = async () => {
    try {
        // 构造筛选条件
        const screenBed = {
            buildingNo: selectCell.value,
            floorNo: selectFloor.value,
            roomNo: selectRoom.value,
        };

        // 调用筛选床位API
        const resScreen = await screenBeds(screenBed);
        console.log("筛选床位返回", resScreen.data);

        // 更新表格数据
        if (resScreen.data.code === 200) {
            filteredBedrooms.value = resScreen.data.data.map((bed: any) => ({
                bedId: bed.bedId,
                buildingNo: bed.buildingNo,
                roomNo: bed.roomNo,
                floorNo: bed.floorNo,
                bedNo: bed.bedNo,
                assignedUserGender: bed.status === '空' ? '' : bed.gender,
                price: bed.price,
            }));
            ElMessage.success('筛选成功');
        } else {
            ElMessage.error('筛选失败: ' + resScreen.data.message);
        }
    } catch (error) {
        console.error('筛选床位失败:', error);
        ElMessage.error('筛选床位失败，请稍后重试');
    }
};
// 获取所有床位信息
const allBeds = async () => {
    try {

        // 调用筛选床位API
        const resScreen = await getAllBeds();
        console.log("筛选床位返回", resScreen.data);

        // 更新表格数据
        if (resScreen.data.code === 200) {
            filteredBedrooms.value = resScreen.data.data.map((bed: any) => ({
                bedId: bed.bedId,
                buildingNo: bed.buildingNo,
                roomNo: bed.roomNo,
                floorNo: bed.floorNo,
                bedNo: bed.bedNo,
                assignedUserGender: bed.status === '空' ? '' : bed.gender,
                price: bed.price,
            }));
            ElMessage.success('筛选成功');
        } else {
            ElMessage.error('筛选失败: ' + resScreen.data.message);
        }
    } catch (error) {
        console.error('筛选床位失败:', error);
        ElMessage.error('筛选床位失败，请稍后重试');
    }
};
// 编辑床位信息
// 弹窗控制
const editDialogVisible = ref(false);
// 编辑表单的数据
const editForm = ref({
    buildingNo: '',
    bedId: '',
    remarks: '',
});
// 编辑按钮方法
const editBed = (row: any) => {
    // 设置当前选中的床位信息到编辑表单
    editForm.value = { ...row }; // 复制当前行的数据到编辑表单
    // 显示弹窗
    editDialogVisible.value = true;
};
// 删除床位的逻辑
const deleteBed = async (row: any) => {
    try {
        console.log('删除床位:', row.bedId);
        const res = await deleteBedAPI(row.bedId);
        console.log("删除床位返回", res);

        // 删除成功后，更新表格数据
        const index = filteredBedrooms.value.findIndex(bed => bed.bedId === row.bedId);
        if (index !== -1) {
            filteredBedrooms.value.splice(index, 1);
        }

    } catch (error) {
        console.error('删除床位失败:', error);
        // 可以在这里添加用户提示，例如使用 Element Plus 的 Message 组件
        ElMessage.error('删除床位失败，请稍后重试');
    }
};
// 编辑楼房信息的弹窗控制
const buildingDialogVisible = ref(false);
// 编辑楼房信息的表单数据
const buildingForm = ref({
    buildingNo: '',
    floorNo: '',
    rooms: [] as { roomNo: string; bedCount: number; price: number }[],
});
// 添加房间
const addRoom = () => {
    buildingForm.value.rooms.push({ roomNo: '', bedCount: 1, price: 0 });
};
// 删除房间
const removeRoom = (index: number) => {
    buildingForm.value.rooms.splice(index, 1);
};
// 保存楼房信息的方法
const saveBuildingInfo = async () => {
    const bedInfoArray: { buildingNo: string; floorNo: string; roomNo: string; bedNo: number; price: number; bedPlace: string; }[] = [];

    // 为每个房间生成多个床位编号，并保存到数组中
    buildingForm.value.rooms.forEach((room) => {
        for (let i = 1; i <= room.bedCount; i++) {
            const bedPlace: string = `${buildingForm.value.buildingNo}-${buildingForm.value.floorNo}-${room.roomNo}-${i}`;
            bedInfoArray.push({
                buildingNo: buildingForm.value.buildingNo,
                floorNo: buildingForm.value.floorNo,
                roomNo: room.roomNo,
                bedPlace: bedPlace,
                price: room.price,
                bedNo: i
            });
        }
    });
    // 在这里你可以将bedInfoArray提交到后端或者更新到前端的数组
    console.log('保存的床位信息数组:', bedInfoArray);
    const res = await addBed(bedInfoArray);
    console.log('提交床位信息反馈', res.data);
    if(res.data.code === 200){
        ElMessage({
            message: '添加成功',
            type: 'success',
        });
    }
    // 关闭弹窗
    buildingDialogVisible.value = false;
    //清空数据
    buildingForm.value = {
        buildingNo: '',
        floorNo: '',
        rooms: [] as { roomNo: string; bedCount: number; price: number }[],
    };
};
// 打开编辑楼房信息弹窗
const openBuildingDialog = () => {
    buildingDialogVisible.value = true;
};

</script>

<style lang="less" scoped>
.setTourPrice {
    width: 10vw;
    display: flex;
    justify-content: flex-end;
}

.el-table {
    margin-top: 20px;
}

.filter-row {
    margin-bottom: 20px;
}

.dialog-footer {
    text-align: right;
}

.el-button {
    margin-left: 10px;
}
</style>